package com.iuchannel.android.provider;

import java.util.Iterator;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.ContentProvider;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.MatrixCursor;
import android.database.MatrixCursor.RowBuilder;
import android.net.Uri;
import android.util.Log;

import com.iuchannel.android.provider.admob.Login;
import com.iuchannel.android.provider.util.PostHttp;
import com.iuchannel.android.provider.util.GetHttp;

public class AdmobProvider extends ContentProvider{

	
	private final static String ADMOB_AUTH_LOGIN_URL="https://api.admob.com/v2/auth/login";
	private final static String ADMOB_SITE_SEARCH_URL="http://api.admob.com/v2/site/search";
	private final static String ADMOB_SITE_STATS_URL="http://api.admob.com/v2/site/stats";
	
	public final static String ROW_ID="_id";
	
	public final static String TABLE_AUTH_LOGIN="login";
	public final static String LOGIN_TOKEN="token";
	public final static String[] PRJ_LOGIN={
		LOGIN_TOKEN,
	};

	public final static String TABLE_SITE_SEARCH="search";
	public final static String SITE_SEARCH_ID="id";
	public final static String SITE_SEARCH_DESCRIPTION="description";
	public final static String SITE_SEARCH_URL="url";
	public final static String SITE_SEARCH_NAME="name";

	public final static String[] PRJ_SITE_SEARCH={
		ROW_ID,
		SITE_SEARCH_ID,
		SITE_SEARCH_DESCRIPTION,
		SITE_SEARCH_URL,
		SITE_SEARCH_NAME,
	};
	
	public final static String TABLE_SITE_STATS="stats";
	public final static String SITE_STATS_SITE_ID="site_id";//"a14f18c22cefb0e",
	public final static String SITE_STATS_REQUESTS="requests";//: 0,
	public final static String SITE_STATS_OVERALL_REQUESTS="overall_requests";//: 0,
	public final static String SITE_STATS_HOUSEAD_REQUESTS="housead_requests";//: 0,
	public final static String SITE_STATS_INTERESTITIAL_REQUESTS="interstitial_requests";//: 0,
	public final static String SITE_STATS_IMPRESSIONS="impressions";//: 0,
	public final static String SITE_STATS_CPC_IMPRESSIONS="cpc_impressions";//: 0,
	public final static String SITE_STATS_CPM_IMPRESSIONS="cpm_impressions";//: 0,
	public final static String SITE_STATS_EXCHANGE_IMPRESSIONS="exchange_impressions";//: 0,
	public final static String SITE_STATS_HOUSEAD_IMPRESSIONS="housead_impressions";//: 0,
	public final static String SITE_STATS_INTERESTITIAL_IMPRESSIONS="interstitial_impressions";//: 0,
	public final static String SITE_STATS_FILL_RATE="fill_rate";//: 0,
	public final static String SITE_STATS_HOUSEAD_FILL_RATE="housead_fill_rate";//: 0,
	public final static String SITE_STATS_OVERALL_FILL_RATE="overall_fill_rate";//: 0,
	public final static String SITE_STATS_CLICKS="clicks";//: 0,
	public final static String SITE_STATS_HOUSEAD_CLICKS="housead_clicks";//: 0,
	public final static String SITE_STATS_CTR="ctr";//: 0,
	public final static String SITE_STATS_HOUSEAD_CTR="housead_ctr";//: 0,
	public final static String SITE_STATS_ECPM="ecpm";//: 0,
	public final static String SITE_STATS_REVENUE="revenue";//: 0,
	public final static String SITE_STATS_CPC_REVENUE="cpc_revenue";//: 0,
	public final static String SITE_STATS_CPM_REVENUE="cpm_revenue";//: 0,
	public final static String SITE_STATS_EXCHANGE_DOWNLOADS="exchange_downloads";//: 0,
	public final static String SITE_STATS_DATE="date";//: "2012-01-08"	
	
	public final static String[] PRJ_SITE_STATS={
		ROW_ID,
		SITE_STATS_SITE_ID,
		SITE_STATS_REQUESTS,
		SITE_STATS_OVERALL_REQUESTS,//="overall_requests";//: 0,
		SITE_STATS_HOUSEAD_REQUESTS,//="housead_requests";//: 0,
		SITE_STATS_INTERESTITIAL_REQUESTS,//="interstitial_requests";//: 0,
		SITE_STATS_IMPRESSIONS,//="impressions";//: 0,
		SITE_STATS_CPC_IMPRESSIONS,//="cpc_impressions";//: 0,
		SITE_STATS_CPM_IMPRESSIONS,//="cpm_impressions";//: 0,
		SITE_STATS_EXCHANGE_IMPRESSIONS,//="exchange_impressions";//: 0,
		SITE_STATS_HOUSEAD_IMPRESSIONS,//="housead_impressions";//: 0,
		SITE_STATS_INTERESTITIAL_IMPRESSIONS,//="interstitial_impressions";//: 0,
		SITE_STATS_FILL_RATE,//="fill_rate";//: 0,
		SITE_STATS_HOUSEAD_FILL_RATE,//="housead_fill_rate";//: 0,
		SITE_STATS_OVERALL_FILL_RATE,//="overall_fill_rate";//: 0,
		SITE_STATS_CLICKS,//="clicks";//: 0,
		SITE_STATS_HOUSEAD_CLICKS,//="housead_clicks";//: 0,
		SITE_STATS_CTR,//="ctr";//: 0,
		SITE_STATS_HOUSEAD_CTR,//="housead_ctr";//: 0,
		SITE_STATS_ECPM,//="ecpm";//: 0,
		SITE_STATS_REVENUE,//="revenue";//: 0,
		SITE_STATS_CPC_REVENUE,//="cpc_revenue";//: 0,
		SITE_STATS_CPM_REVENUE,//="cpm_revenue";//: 0,
		SITE_STATS_EXCHANGE_DOWNLOADS,//="exchange_downloads";//: 0,
		SITE_STATS_DATE,//="date";//: "2012-01-08"
	};

	
	private  UriMatcher Matcher;
	private static final int MATCH_LOGIN=0x010;
	private static final int MATCH_SEARCH=0x020;
	private static final int MATCH_STATS=0x030;
		
	private void makeMatcher(){
		String packageName=getContext().getPackageName();
		String uri=packageName+".AdmobProvider";
		
		Matcher = new UriMatcher(UriMatcher.NO_MATCH);
		Matcher.addURI(uri, TABLE_AUTH_LOGIN, MATCH_LOGIN);
		Matcher.addURI(uri, TABLE_SITE_SEARCH, MATCH_SEARCH);
		Matcher.addURI(uri, TABLE_SITE_STATS, MATCH_STATS);
	}
	
	@Override
	public boolean onCreate() {
		makeMatcher();
		
		return false;
	}

	@Override
	public Cursor query(Uri uri, String[] projection, String selection,String[] selectionArgs, String sortOrder) {
		log("Query Called : "+uri.toString());
		Cursor c=null;
		//String where = selection;	
		int matcher=Matcher.match(uri);
		switch(matcher){
		case MATCH_LOGIN:
			c=requestLogin(uri);
			break;
		case MATCH_SEARCH:
			c=requestSearch(uri);
			break;
		case MATCH_STATS:
			c=requestStats(uri);
			break;
		default:
			break;
		}
		
		if(projection!=null && projection.length>0){
			log("JSON:query() - projection not null");
			if(c!=null){
				c=getCursorWithProjection(c,projection);
			}
		}
		
		return c;		
	}

	@Override
	public int update(Uri arg0, ContentValues arg1, String arg2, String[] arg3) {
		// TODO Auto-generated method stub
		return 0;
	}
	
	@Override
	public int delete(Uri arg0, String arg1, String[] arg2) {
		// TODO Auto-generated method stub
		return 0;
	}

	@Override
	public String getType(Uri arg0) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Uri insert(Uri arg0, ContentValues arg1) {
		// TODO Auto-generated method stub
		return null;
	}
	
	private void log(String s){
		Log.d("AdmobProvider", s);
	}
	
	private static Cursor getCursorWithProjection(Cursor c, String[] projection){
		MatrixCursor m=new MatrixCursor(projection);
		c.moveToFirst();
		for(int i=0;i<c.getCount();i++){
			RowBuilder r=m.newRow();
			for(String s:projection){ 
				int index=c.getColumnIndex(s);
				if(index !=-1){
					String value=c.getString(index);
					r.add(value);
				}else{
					r.add("");
				}
			}
		}
		return m;
	}
	private Cursor requestStats(Uri uri){
		//String clientKey=uri.getQueryParameter("client_key");
		//String token=uri.getQueryParameter("token");
		//List<String> siteIds=uri.getQueryParameters("site_id[]");
		//String siteId=uri.getQueryParameter("site_id");
		//url=url+"?client_key="+clientKey+"&token="+token;

		String query=uri.getQuery();
		String url=ADMOB_SITE_STATS_URL;
		url=url+"?"+query;
		log("Get URL="+url);
		
		String result=GetHttp.getUrl(url);
		
		if(result==null || result.length()==0){
			log("Result null : return");
			return null;
		}
		log(result);
		
		MatrixCursor m=new MatrixCursor(PRJ_SITE_STATS);
		try {
			JSONObject j = new JSONObject(result);
			JSONArray ja=j.getJSONArray("data");
			JSONObject first=(JSONObject)ja.get(0);
			Iterator<String> iter=first.keys();
			int count=0;
			for(int i=0;i<ja.length();i++){
				JSONObject jo=(JSONObject)ja.getJSONObject(i);
				RowBuilder r=m.newRow();
				for(String s:PRJ_SITE_STATS){
					if(s.equals(ROW_ID)){
						r.add(count++);
					}else{
						String itemString=jo.getString(s);
						r.add(itemString);					
					}					
				}
			}
			
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			m=new MatrixCursor(PRJ_SITE_STATS);
			e.printStackTrace();
		}
		
		
		return m;
	}
	private Cursor requestSearch(Uri uri){
		
		String clientKey=uri.getQueryParameter("client_key");
		String token=uri.getQueryParameter("token");
		
		String url=ADMOB_SITE_SEARCH_URL;
		url=url+"?client_key="+clientKey+"&token="+token;
		log("Get URL="+url);
		String result=GetHttp.getUrl(url);
		
		if(result==null || result.length()==0){
			log("Result null : return");
			return null;
		}
		
		MatrixCursor m=new MatrixCursor(PRJ_SITE_SEARCH);
		try {
			JSONObject j=new JSONObject(result);
			
			JSONArray jsonArray=j.getJSONArray("data");
			int count=0;
			for(int i=0;i<jsonArray.length();i++){
				JSONObject jsonData=(JSONObject)jsonArray.get(i);
				RowBuilder r=m.newRow();
				for(String s:PRJ_SITE_SEARCH){
					if(s.equals(ROW_ID)){
						r.add(count++);
					}else{
						String itemString=jsonData.getString(s);
						r.add(itemString);					
					}
				}				
			}

		} catch (JSONException e) {
			// Count=0, Communications OK, Error with JSON
			m=new MatrixCursor(PRJ_SITE_SEARCH);
			e.printStackTrace();
		}
		
		log("Total row="+m.getCount());
		
		return m;
	}
	
	private Cursor requestLogin(Uri uri){
		
		String _email=uri.getQueryParameter("email");
		String _password=uri.getQueryParameter("password");
		String _apiKey=uri.getQueryParameter("apikey");
		
		String url=ADMOB_AUTH_LOGIN_URL;
		url=url+"?client_key="+_apiKey+"&email="+_email+"&password="+_password;
		log("PostUrl="+url);
		String result=PostHttp.postUrl(url);
		
		if(result==null || result.length()==0){
			log("Result null : return");
			return null;
		}
		
		MatrixCursor m=new MatrixCursor(PRJ_LOGIN);
		try {
			JSONObject j=new JSONObject(result);
			RowBuilder r=m.newRow();
			
			for(String s:PRJ_LOGIN){
				if(s.equals(LOGIN_TOKEN)){
					JSONObject jsonData=j.getJSONObject("data");
					String token=jsonData.getString("token");
					r.add(token);
				}
			}
			
		} catch (JSONException e) {
			// Count=0, Communications OK, Error with JSON
			m=new MatrixCursor(PRJ_LOGIN);
			e.printStackTrace();
		}
		
		return m;
	}
	
}